﻿using System;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.Services;
using QuanLyHopDong.Biz;
using QuanLyHopDong.Biz.Model;
using QuanLyHopDong.Web.Common;
using Resources;

namespace QuanLyHopDong.Web.HopDong
{
    public partial class QuyetToan : System.Web.UI.Page
    {
        #region Properties

        private static QuyetToanBiz _quyetToanBiz;

        private static QuyetToanBiz QuyetToanManager
        {
            get { return _quyetToanBiz ?? (_quyetToanBiz = new QuyetToanBiz()); }
        }

        private int _hopDongId;

        private int HopDongId
        {
            get
            {
                if (_hopDongId <= 0)
                    int.TryParse(Request.QueryString["hopDongId"], out _hopDongId);
                return _hopDongId;
            }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadHopDongData();
                LoadQuyetToan();
            }
        }

        protected void btnSaveThanhToan_Click(object sender, EventArgs e)
        {
            decimal soTien;
            decimal.TryParse(txtSoTien.Text.Trim(), out soTien);

            var thanhToan = new ThanhToan
            {
                SoTien = soTien,
                HopDongId = HopDongId,
                DaThanhToan = rbtDaThanhToan.Checked,
                Ten = txtNoiDung.Text.Trim()
            };

            if (fileChungTu.HasFile)
            {
                var fileName = Path.GetFileName(fileChungTu.PostedFile.FileName);

                // file upload
                var folderPath = Server.MapPath(string.Format("~/Files/HopDong/{0}", HopDongId));
                // create folder
                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);

                // save file
                var filePathFull = folderPath + "/" + fileName;
                if (File.Exists(filePathFull))
                    File.Delete(filePathFull);
                fileChungTu.PostedFile.SaveAs(filePathFull);

                thanhToan.ChungTu = fileName;
            }

            QuyetToanManager.AddThanhToan(thanhToan);

            Response.Redirect(string.Format("QuyetToan.aspx?hopDongId={0}", HopDongId));
        }

        protected void btnUpdateThanhToan_Click(object sender, EventArgs e)
        {
            decimal soTien;
            decimal.TryParse(txtSoTienEdit.Text.Trim(), out soTien);

            var id = int.Parse(hidThanhToanId.Value);
            var currentThanhToan = QuyetToanManager.GetThanhToan(id);

            if (currentThanhToan == null) return;

            var thanhToan = new ThanhToan
            {
                Id = id,
                SoTien = soTien,
                HopDongId = HopDongId,
                DaThanhToan = rbtDaThanhToanEdit.Checked,
                Ten = txtNoiDungEdit.Text.Trim()
            };

            if (fileChungTuEdit.HasFile)
            {
                // delete old file
                if (!string.IsNullOrEmpty(currentThanhToan.ChungTu))
                {
                    var filePath =
                        Server.MapPath(string.Format("~/Files/HopDong/{0}/{1}", HopDongId,
                            currentThanhToan.ChungTu));
                    QuyetToanManager.DeleteChungTu(filePath, id);
                }

                var fileName = Path.GetFileName(fileChungTuEdit.PostedFile.FileName);

                // file upload
                var folderPath = Server.MapPath(string.Format("~/Files/HopDong/{0}", HopDongId));

                // create folder
                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);

                // save file
                var filePathFull = folderPath + "\\" + fileName;
                if (File.Exists(filePathFull))
                    File.Delete(filePathFull);
                fileChungTu.PostedFile.SaveAs(filePathFull);

                thanhToan.ChungTu = fileName;
            }

            QuyetToanManager.UpdateThanhToan(thanhToan);

            Response.Redirect(string.Format("QuyetToan.aspx?hopDongId={0}", HopDongId));
        }

        protected void btnSaveQuyetToan_Click(object sender, EventArgs e)
        {
            var quyetToan = new Biz.Model.QuyetToan
            {
                HopDongId = HopDongId,
                CreatedDate = DateTime.Now,
                ModifiedDate = DateTime.Now,
                CreatedBy = WebCommon.CurrrentEmployee.Id,
                ModifiedBy = WebCommon.CurrrentEmployee.Id
            };

            decimal giaTriQuyetToan;
            if (decimal.TryParse(txtGiaTriQuyetToan.Text.Trim(), out giaTriQuyetToan))
            {
                quyetToan.GiaTriQuyetToan = giaTriQuyetToan;
            }

            decimal giaTriVatTuQuyetToan;
            if (decimal.TryParse(txtGiaTriVatTuQuyetToan.Text.Trim(), out giaTriVatTuQuyetToan))
            {
                quyetToan.GiaTriVatTu = giaTriVatTuQuyetToan;
            }

            decimal giaTriNhanCongQuyetToan;
            if (decimal.TryParse(txtGiaTriNhanCongQuyetToan.Text.Trim(), out giaTriNhanCongQuyetToan))
            {
                quyetToan.GiaTriNhanCong = giaTriNhanCongQuyetToan;
            }

            decimal chiPhiKhac;
            if (decimal.TryParse(txtChiPhiKhacQuyetToan.Text.Trim(), out chiPhiKhac))
            {
                quyetToan.ChiPhiKhac = chiPhiKhac;
            }

            decimal giaTriHopDongChuaVat;
            if (decimal.TryParse(txtGiaTriHopDongChuaVATQuyetToan.Text.Trim(), out giaTriHopDongChuaVat))
            {
                quyetToan.GiaTriHopDongChuaVAT = giaTriHopDongChuaVat;
            }

            decimal vat;
            if (decimal.TryParse(txtVatQuyetToan.Text.Trim(), out vat))
            {
                quyetToan.VAT = vat;
            }

            //decimal tongGiaTriQuyetToan;
            //if (decimal.TryParse(txtTongGiaTriQuyetToan.Text.Trim(), out tongGiaTriQuyetToan))
            //{
            //    quyetToan.TongGiaTriQuyetToan = tongGiaTriQuyetToan;
            //}

            DateTime ngayQuyetToan;
            if (DateTime.TryParseExact(txtNgayQuyetToan.Text.Trim(), GlobalStrings.DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out ngayQuyetToan))
            {
                quyetToan.NgayQuyetToan = ngayQuyetToan;
            }

            try
            {
                QuyetToanManager.CreateQuyetToan(quyetToan);
                Response.Redirect(string.Format("QuyetToan.aspx?hopDongId={0}#tabs-2", HopDongId));
            }
            catch (ApplicationException appEx)
            {
                lblErrorMessage.Text = WebCommon.GetGlobalString(appEx.Message);
            }
        }

        protected void btnSaveQuyetToanNoiBo_Click(object sender, EventArgs e)
        {
            decimal soTien;
            decimal.TryParse(txtQuyetToanNoiBoSoTien.Text.Trim(), out soTien);

            var quyetToanNoiBo = new QuyetToanNoiBo
            {
                HopDongId = HopDongId,
                SoTien = soTien,
                Ten = txtQuyetToanNoiBoTen.Text.Trim(),
                LoaiQuyetToanId = short.Parse(ddlLoaiQuyetToan.SelectedValue)
            };

            if (fileQuyetToanNoiBoChungTu.HasFile)
            {
                var fileName = Path.GetFileName(fileQuyetToanNoiBoChungTu.PostedFile.FileName);

                // file upload
                var folderPath = Server.MapPath(string.Format("~/Files/HopDong/{0}", HopDongId));
                // create folder
                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);

                // save file
                var filePathFull = folderPath + "/" + fileName;
                if (File.Exists(filePathFull))
                    File.Delete(filePathFull);
                fileQuyetToanNoiBoChungTu.PostedFile.SaveAs(filePathFull);

                quyetToanNoiBo.ChungTu = fileName;
            }

            QuyetToanManager.AddQuyetToanNoiBo(quyetToanNoiBo);

            Response.Redirect(string.Format("QuyetToan.aspx?hopDongId={0}#tabs-3", HopDongId));
        }

        protected void btnUpdateQuyetToanNoiBo_Click(object sender, EventArgs e)
        {
            decimal soTien;
            decimal.TryParse(txtQuyetToanNoiBoSoTienEdit.Text.Trim(), out soTien);

            var id = int.Parse(hidQuyetToanNoiBoId.Value);
            var currentQuyetToanNoiBo = QuyetToanManager.GetQuyetToanNoiBo(id);

            if (currentQuyetToanNoiBo == null) return;

            var quyetToanNoiBo = new QuyetToanNoiBo
            {
                Id = id,
                SoTien = soTien,
                HopDongId = HopDongId,
                Ten = txtQuyetToanNoiBoTenEdit.Text.Trim(),
                LoaiQuyetToanId = short.Parse(ddlLoaiQuyetToanEdit.SelectedValue)
            };

            if (fileQuyetToanNoiBoChungTuEdit.HasFile)
            {
                // delete old file
                if (!string.IsNullOrEmpty(currentQuyetToanNoiBo.ChungTu))
                {
                    var filePath =
                        Server.MapPath(string.Format("~/Files/HopDong/{0}/{1}", HopDongId,
                            currentQuyetToanNoiBo.ChungTu));
                    QuyetToanManager.DeleteQuyetToanNoiBoChungTu(filePath, id);
                }

                var fileName = Path.GetFileName(fileQuyetToanNoiBoChungTuEdit.PostedFile.FileName);

                // file upload
                var folderPath = Server.MapPath(string.Format("~/Files/HopDong/{0}", HopDongId));

                // create folder
                if (!Directory.Exists(folderPath))
                    Directory.CreateDirectory(folderPath);

                // save file
                var filePathFull = folderPath + "\\" + fileName;
                if (File.Exists(filePathFull))
                    File.Delete(filePathFull);
                fileQuyetToanNoiBoChungTuEdit.PostedFile.SaveAs(filePathFull);

                quyetToanNoiBo.ChungTu = fileName;
            }

            QuyetToanManager.UpdateQuyetToanNoiBo(quyetToanNoiBo);

            Response.Redirect(string.Format("QuyetToan.aspx?hopDongId={0}#tabs-3", HopDongId));
        }

        #endregion

        #region WebMethods
        
        [WebMethod]
        public static object ThanhToanList(int hopDongId)
        {
            var thanhToans = QuyetToanManager.GetThanhToans(hopDongId);
            return new { Result = "OK", Records = thanhToans };
        }

        [WebMethod]
        public static object GetTotalThanhToan(int hopDongId)
        {
            return QuyetToanManager.GetTotalThanhToan(hopDongId);
        }

        [WebMethod]
        public static object DeleteChungTu(int thanhToanId)
        {
            var folderPath = HttpContext.Current.Server.MapPath("~/Files/HopDong");
            QuyetToanManager.DeleteFileChungTu(folderPath, thanhToanId);
            return new { Result = "OK" };
        }

        [WebMethod]
        public static object ThanhToanDelete(int Id)
        {
            var folderPath = HttpContext.Current.Server.MapPath("~/Files/HopDong");
            QuyetToanManager.DeleteThanhToan(folderPath, Id);
            return new { Result = "OK" };
        }

        [WebMethod]
        public static object QuyetToanNoiBoList(int hopDongId)
        {
            var records = QuyetToanManager.GetQuyetToanNoiBos(hopDongId);
            return new { Result = "OK", Records = records };
        }

        [WebMethod]
        public static object QuyetToanNoiBoDelete(int Id)
        {
            var folderPath = HttpContext.Current.Server.MapPath("~/Files/HopDong");
            QuyetToanManager.DeleteQuyetToanNoiBo(folderPath, Id);
            return new { Result = "OK" };
        }

        [WebMethod]
        public static object DeleteQuyetToanNoiBoChungTu(int quyetToanNoiBoId)
        {
            var folderPath = HttpContext.Current.Server.MapPath("~/Files/HopDong");
            QuyetToanManager.DeleteFileQuyetToanNoiBoChungTu(folderPath, quyetToanNoiBoId);
            return new { Result = "OK" };
        }

        [WebMethod]
        public static object GetTotalQuyetToan(int hopDongId)
        {
            return QuyetToanManager.GetTotalQuyetToan(hopDongId);
        }

        #endregion

        #region Helpers

        private void LoadHopDongData()
        {
            var hopDong = QuyetToanManager.GetHopDongData(HopDongId);
            if (hopDong != null)
            {
                ltrSoHopDong.Text = hopDong.SoHopDong;
                ltrTenHopDong.Text = hopDong.TenHopDong;
                ltrGiaTriChuaVat.Text = string.Format("{0:N0}", hopDong.GiaTriHopDongChuaVAT);
                ltrGiaTriVat.Text = string.Format("{0:N0}", hopDong.VAT);
                ltrGiaTriNhanCong.Text = string.Format("{0:N0}", hopDong.GiaTriNhanCong);
                ltrGiaTriTong.Text = string.Format("{0:N0}", hopDong.TongGiaTriHopDong);
                ltrGiaTriVatTu.Text = string.Format("{0:N0}", hopDong.GiaTriVatTu);
            }
        }

        private void LoadQuyetToan()
        {
            var quyetToan = QuyetToanManager.GetQuyetToan(HopDongId);
            if (quyetToan != null)
            {
                txtGiaTriQuyetToan.Text = string.Format("{0:N0}", quyetToan.GiaTriQuyetToan);
                txtGiaTriVatTuQuyetToan.Text = string.Format("{0:N0}", quyetToan.GiaTriVatTu);
                txtGiaTriNhanCongQuyetToan.Text = string.Format("{0:N0}", quyetToan.GiaTriNhanCong);
                txtChiPhiKhacQuyetToan.Text = string.Format("{0:N0}", quyetToan.ChiPhiKhac);
                txtGiaTriHopDongChuaVATQuyetToan.Text = string.Format("{0:N0}", quyetToan.GiaTriHopDongChuaVAT);
                txtVatQuyetToan.Text = string.Format("{0:N0}", quyetToan.VAT);
                //txtTongGiaTriQuyetToan.Text = string.Format("{0:N0}", quyetToan.TongGiaTriQuyetToan);
                txtNgayQuyetToan.Text = quyetToan.NgayQuyetToan.HasValue
                    ? quyetToan.NgayQuyetToan.Value.ToString(GlobalStrings.DateFormat)
                    : string.Empty;
            }
        }

        #endregion
    }
}